<?php
namespace BLL\DataModel;
use Exception;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

//namespace DataModel;

/**
 * Base Class DataDescription
 *
 * contains common fields of the data
 *
 * @author David Wu
 */
abstract class  DataDescription {
    
    /**
     * The name of the model.
     *
     * @var string
     */
    public $name = null;
    
    /**
     * If this node/item can be null.
     * true: can not ne null
     * false: can be null
     *
     * @var bool
     */
    public $isNecessary = false;
    
    /**
     * If this node/item is discarded.
     * true: can not ne null
     * false: can be null
     *
     * @var bool
     */
    public $isDescarded = false;
    

    /**
     * Read attibute value from JSon Object.
     * If the key exist return the value,
     * if not return the default( null ignored).
     * 
     * @_jsonObject  json object
     * @key string
     * @type expected datatype of the value
     * @default default value
     */
    protected function readAttrFromJSon($_jsonObject,$key,$type,$default=null){
        if(isset($_jsonObject->{$key})){
            $this->{$key} = DataType::getValueFromString($type,$_jsonObject->{$key});
        }else{
            if (!empty($default)) {
                $this->{$key} = $default;
            }
        }
    }
    
    /**
     * Read base fields from JSon Object.
     * 
     * @Exception Wrong JSon Object
     */
    protected function loadFromJSONObject($_jsonObject){
        if(!isset($_jsonObject->name)){
            throw new Exception("Error In JSON Object , Expect attribute 'name'");
        }
        $this->name = $_jsonObject->name;
        $this->readAttrFromJSon( $_jsonObject, "isNecessary",  DataType::Bool);
        $this->readAttrFromJSon( $_jsonObject, "isDescarded",  DataType::Bool);
        
    }
}
